<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="500px"
    append-to-body
    :before-close="close"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="130px">
      <el-form-item label="模板名称" prop="contractTemplateName">
        <el-input v-model="form.contractTemplateName" clearable placeholder="请输入合约名称"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="templateState">
        <el-radio-group v-model="form.templateState">
          <el-radio label="0">显示</el-radio>
          <el-radio label="1">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { debounce } from '@/utils'
import { addContractTemplate, updateContractTemplate } from '@/api/contract/template'

export default {
  name: 'Setting',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    title: {
      default: '设置'
    },
    formData: {}
  },
  data() {
    return {
      visible: false,
      form: {
        name: ''
      },
      rules: {
        contractTemplateName: [
          { required: true, message: '请输入合约名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        templateState: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      } // 表单验证规则
    }
  },
  watch: {
    value(newVal, oldVal) {
      this.visible = newVal // 监测value的变化，并赋值。
      if (newVal) {
        this.form = this.formData
        this.init()
      }
    },
    visible(val) {
      this.$emit('input', val) // 此处监测showMask目的为关闭弹窗时，重新更换value值，注意emit的事件一定要为input。
    }
  },
  methods: {
    init() {
      this.reset()
    },
    reset() {
      this.resetForm('form')
    },
    submit: debounce(function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.contractTemplateId != undefined) {
            updateContractTemplate(this.form).then((response) => {
              this.$modal.msgSuccess(response.msg)
              this.$emit('success')
            })
          } else {
            addContractTemplate(this.form).then((response) => {
              this.$modal.msgSuccess(response.msg)
              this.$emit('success')
            })
          }
          this.close()
        }
      })
    }, 500),
    close() {
      this.reset()
      this.visible = false
    }
  }
}
</script>


<style scoped lang="scss">

</style>
